﻿using System;
using System.Configuration;
using System.Threading;
using System.Web;
using Common.Logging;

namespace NPMonitor.Implementation.Mail
{
    public class MailModule : System.Web.IHttpModule
    {
        static Timer eventTimer;
        private ILog logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 实现接口的Init方法
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            if (eventTimer == null)
            {
                eventTimer = new Timer(new TimerCallback(ScheduledEventWorkCallback), context.Context, 60000, SendMailTimerMinutesInterval * 60000);
            }
        }

        private void ScheduledEventWorkCallback(object sender)
        {
            try
            {
                if (SendMailEnabled)
                {
                    //Do Send Mail Task
                    SendMail sendMail = new SendMail();
                    sendMail.Execute();
                }
                //when machine online, Scheduled/Runonce job statue update from Pending to Scheduled/Ready
                //when machine offline, Scheduled job statue update from Scheduled to Peinding
                StoreManager.Current.JobStore.RefreshJobStatus();
            }
            catch(Exception ex)
            {
                logger.Error("Error:ScheduledEventWorkCallback", ex);
            }
        }

        private bool SendMailEnabled
        {
            get
            {
                string mailEnabled = ConfigurationManager.AppSettings["SendMailEnabled"];
                return Convert.ToBoolean(mailEnabled);
            }
        }

        private int SendMailTimerMinutesInterval
        {
            get
            {
                string sendMailTimerMinutesInterval = ConfigurationManager.AppSettings["SendMailTimerMinutesInterval"];
                return Convert.ToInt32(sendMailTimerMinutesInterval);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            GC.Collect();
        }

        #endregion
    }
}
